package com.dongdongshop.aldy;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dongdongshop.data.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class ExamPhone {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    public Result code(String phone) throws Exception {
        Client client = createClient("LTAI4GCbdwnjCGwQj9Z3tr3N", "27ih4pc1W1tqey9X4mmCy1JUotAX7L");
        String s = RandomUtil.randomNumbers(4);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setTemplateParam("{\"sms_code\":\""+ s +"\"}")
                .setPhoneNumbers(phone)
                .setTemplateCode("SMS_162522027")
                .setSignName("东科创想");
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse send = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());
            redisTemplate.opsForValue().set(phone,s,15, TimeUnit.MINUTES);
            SendSmsResponseBody body = send.getBody();
            System.out.println(body.message);
            System.out.println(body.code);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }
}
